package com.chen.palmar.common.override;

import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

/**
 * viewpager的fragment的适配器
 */
public abstract class FragmentViewPagerAdapter extends PagerAdapter {

    private final FragmentManager manager;

    public FragmentViewPagerAdapter(FragmentManager managerFragment) {
        manager = managerFragment;
    }

    public abstract Fragment getItem(int position);

    public abstract int getCount();


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = getItem(position);
        if (!fragment.isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(fragment, "HomeFragment" + String.valueOf(position));
            ft.commit();
            manager.executePendingTransactions();
        }
        if (fragment.getView().getParent() == null) {
            container.addView(fragment.getView());
        }
        return fragment.getView();
    }

    @Override
    public void startUpdate(ViewGroup container) {

    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(((View) object));
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {

    }
}

